/*
 * Copyright 2010 Kevin L'Huillier <klhuillier@gmail.com>
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package org.lhuillier.pwsafe.io.v3;


import org.bouncycastle.util.Arrays;
import org.lhuillier.pwsafe.io.StretchedKey;
import org.lhuillier.pwsafe.io.codec.BinConverter;


public class V3StretchedKey implements StretchedKey {
    private final byte[] key;
    private final byte[] salt;
    private final int iterations;
    private final Crypto crypto;
    private final BinConverter binConv;
    private final V3KeyStretcher stretcher;
    
    V3StretchedKey(byte[] key, byte[] salt, int iterations, 
            Crypto crypto, BinConverter binConv, V3KeyStretcher stretcher) {
        this.key = key.clone();
        this.salt = salt.clone();
        this.iterations = iterations;
        this.crypto = crypto;
        this.binConv = binConv;
        this.stretcher = stretcher;
    }

    @Override
    public byte[] getKey() {
        return key.clone();
    }

    @Override
    public byte[] getSalt() {
        return salt.clone();
    }

    @Override
    public int getIterations() {
        return iterations;
    }

    @Override
    public boolean validPassword(String password) {
        byte[] pwBytes = binConv.writeString(password);
        byte[] actual = crypto.stretchKey(pwBytes, salt, iterations);
        return Arrays.areEqual(key, actual);
    }

    @Override
    public StretchedKey resalt(String password) {
        return stretcher.resalt(this, password);
    }
}
